package com.market.cash.utils.helper

import com.market.cash.CashRootApps
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.utils.CashRootAesUtil
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.log.CashRootLog
import com.market.cash.utils.log.JsonFormat
import com.market.network.OkHttp
import com.market.network.callback.StringCallback
import com.market.network.model.Response
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/29 18:06
 * @Annotation：保存自定义数据接口 参数
 */
object CashRootCustomDataHelper {

    /**
     * userName                         : 用户名
     * userBirthday                     ： 用户生日（时间戳 秒）
     * userAvatarUrl                    ： 用户头像链接
     */

    /**
     * 获取保存的自定义数据
     */
    fun getCashRootCustomData(): JSONObject {
        val customData = SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_CUSTOM_DATA)
        if (customData.isEmpty()){
            return JSONObject()
        }
        return JSONObject(customData)
    }

    /**
     * 获取用户昵称
     */
    fun getCashRootCustomUserName(): String{
        val data = getCashRootCustomData()
        return data.optString("userName","Hello")
    }

    /**
     * 获取用户头像id
     */
    fun getCashRootCustomUserAvatarUrl(): String{
        val data = getCashRootCustomData()
        return data.optString("userAvatarUrl","")
    }

    /**
     * 获取用户生日(时间戳 秒)
     */
    fun getCashRootCustomUserBirthday(): String{
        val data = getCashRootCustomData()
        return data.optString("userBirthday","")
    }

    /**
     * 保存用户昵称
     */
    fun saveCashRootCustomUserNameAction(userName: String){
        val obj = getCashRootCustomData()
        obj.put("userName",userName)
        saveCashRootCustomDataAction(obj)
    }

    /**
     * 保存用户头像id
     */
    fun saveCashRootCustomUserAvatar(imgUrl: String){
        val obj = getCashRootCustomData()
        obj.put("userAvatarUrl",imgUrl)
        saveCashRootCustomDataAction(obj)
    }

    /**
     * 保存用户生日(时间戳 秒)
     */
    fun saveCashRootCustomUserBirthday(timestamp: String){
        val obj = getCashRootCustomData()
        obj.put("userBirthday",timestamp)
        saveCashRootCustomDataAction(obj)
    }

    /**
     * 获取自定义数据
     */
    fun loadCashRootCustomDataAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_CUSTOM_DATA_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_LOAD_CUSTOM_PARAMS_PATH)
        }
        val aesParams = CashRootAesUtil.encryptDefault(params.toString())
        CashRootLog.e("HttpUrl：  $httpUrl")
        CashRootLog.e("HttpParams： $params")
        CashRootLog.e("HttpParams AES：  $aesParams")

        OkHttp.post<String>(httpUrl) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .upString(aesParams)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val body = response.body()
                    val result = CashRootAesUtil.decryptDefault(body)
                    if (result.isNotEmpty()){
                        Thread { CashRootLog.i(JsonFormat.format(result)) }.start()
                        val data = JSONObject(result)
                        when(data.optInt("code")) {
                            0 -> {//成功
                                val obj = data.optJSONObject("obj")
                                if (obj != null && obj.has("userInfo")){
                                    val userInfo = obj.optString("userInfo")
                                    //保存自定义数据
                                    SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_CUSTOM_DATA,userInfo.toString())
                                    //通知自定义数据刷新完成
                                    CashRootApps.app.publisher.publish(CashRootEventData(CashRootEventData.TYPE.CASHROOT_CUSTOM_DATA_REFRESHED))
                                }
                            }
                            else -> {
                            }
                        }
                    }
                }

                override fun onError(response: Response<String>) {
                }
                override fun onFinish() {
                }
            })
    }

    /**
     * 保存数据
     */
    private fun saveCashRootCustomDataAction(obj: JSONObject,callback: IHttpCallback? = null){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_CUSTOM_DATA_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.CASHROOT_API_SAVE_CUSTOM_PARAMS_PATH)
            put("userInfo",obj.toString())
        }

        val aesParams = CashRootAesUtil.encryptDefault(params.toString())
        CashRootLog.e("HttpUrl：  $httpUrl")
        CashRootLog.e("HttpParams： $params")
        CashRootLog.e("HttpParams AES：  $aesParams")

        OkHttp.post<String>(httpUrl) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .upString(aesParams)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val body = response.body()
                    val result = CashRootAesUtil.decryptDefault(body)
                    if (result.isNotEmpty()){
                        Thread { CashRootLog.i(JsonFormat.format(result)) }.start()
                        val data = JSONObject(result)
                        callback?.onRequestSuccess(data)
                        when(data.optInt("code")) {
                            0 -> {//成功
                                val obj = data.optJSONObject("obj")
                                if (obj != null){
                                    //保存成功 再更新数据
                                    loadCashRootCustomDataAction()
                                }
                            }
                        }
                    } else {
                        val errorObj = JSONObject()
                        errorObj.put("errorCode",-1)
                        errorObj.put("errorMsg","http request error $result")
                        callback?.onRequestError(errorObj)
                    }
                }

                override fun onError(response: Response<String>) {
                    val errorObj = JSONObject()
                    errorObj.put("errorCode",response.code())
                    errorObj.put("errorMsg",response.message())
                    callback?.onRequestError(errorObj)
                }
                override fun onFinish() {
                    callback?.onRequestFinish()
                }
            })
    }
}